<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author LYS
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'barcode:basBarM:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #basBarRdsList>
        <BasicTable
          @register="registerBasBarRdsTable"
          @row-click="handleBasBarRdsRowClick"
        />
        <!-- <a-button class="mt-2" @click="handleBasBarRdsAdd" v-auth="'barcode:basBarM:edit'">
          <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button> -->
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsBarcodeBasBarMForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasBarM, basBarMSave, basBarMForm, basBarMGenSnCode } from '/@/api/barcode/basBarM';
  import { basPkgMGetGenPkgInfo } from '/@/api/pkg/basPkgM';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('barcode.basBarM');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<BasBarM>({} as BasBarM);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('生产条码') : t('编辑条码'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('包装'),
      field: 'ccode',
      fieldLabel: 'cname',
      component: 'ListSelect',
      componentProps: ({ formModel }) => {
        console.log('formModel', formModel);
        return {
          selectType: 'basInvPackSelect',
          onSelect: async (selectData) => {
            console.log('selectData', selectData);
            formModel['invCode'] = selectData[0]['invCode'];
            formModel['boxType'] = selectData[0]['barType'];
          },
        }
      },
      required: true,
    },
    {
      label: t('批次号'),
      field: 'cbeach',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('存货编码'),
      field: 'invCode',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      required: true,
      dynamicDisabled: true,
    },
    {
      label: t('条码类型'),
      field: 'boxType',
      component: 'Select',
      componentProps: {
        dictType: 'btdm_bar_type',
        allowClear: true,
      },
      required: true,
      dynamicDisabled: true,
    },
    {
      label: t('数量'),
      field: 'iqty',
      component: 'Input',
      componentProps: ({ formModel }) => {
        return {
          maxlength: 8,
          onChange: async (e) => {
            const params = { ccode: formModel['ccode'], genQty: e.target.value };
            const res = await basPkgMGetGenPkgInfo(params);
            console.log('res', res);
            basBarRdsTable.setTableData(res.data.basPkgCList);
          }
        }
      },
      rules: [{ required: true }, { pattern: /^\d+$/, message: t('请输入一个正整数') }],
    },
    {
      label: t('生产日期'),
      field: 'scDate',
      component: 'DatePicker',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('条码信息明细'),
      field: 'basBarRdsList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'basBarRdsList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerBasBarRdsTable, basBarRdsTable] = useTable({
    // actionColumn: {
    //   width: 60,
    //   actions: (record: Recordable) => [
    //     {
    //       icon: 'i-ant-design:delete-outlined',
    //       color: 'error',
    //       popConfirm: {
    //         title: '是否确认删除',
    //         confirm: handleBasBarRdsDelete.bind(this, record),
    //       },
    //       auth: 'barcode:basBarM:edit',
    //     },
    //   ],
    // },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setBasBarRdsTableData(_res: Recordable) {
    basBarRdsTable.setColumns([
      {
        title: t('条码类型'),
        dataIndex: 'barType',
        width: 130,
        align: 'center',
        dictType: 'btdm_bar_type',
        editRow: true,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'btdm_bar_type',
          allowClear: true,
        },
        editRule: true,
      },
      {
        title: t('生成数量'),
        dataIndex: 'sjGenQty',
        width: 130,
        align: 'center',
      },
      {
        title: t('层级'),
        dataIndex: 'level',
        width: 130,
        align: 'center',
      },
    ]);
    basBarRdsTable.setTableData(record.value.basBarRdsList || []);
  }

  function handleBasBarRdsRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleBasBarRdsAdd() {
    basBarRdsTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleBasBarRdsDelete(record: Recordable) {
    basBarRdsTable.deleteTableDataRecord(record);
  }

  async function getBasBarRdsList() {
    let basBarRdsListValid = true;
    let basBarRdsList: Recordable[] = [];
    for (const record of basBarRdsTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        basBarRdsListValid = false;
      }
      basBarRdsList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of basBarRdsTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      basBarRdsList.push({
        ...record,
        status: '1',
      });
    }
    if (!basBarRdsListValid) {
      throw { errorFields: [{ name: ['basBarRdsList'] }] };
    }
    return basBarRdsList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await basBarMForm(data);
    record.value = (res.basBarM || {}) as BasBarM;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setBasBarRdsTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      // data.basBarRdsList = await getBasBarRdsList();
      console.log('submit', data, record);
      // console.log('submit', params, data, record);
      // data.ccode = record.value.ccode;
      data.pkgId = data.ccode;
      const res = await basBarMGenSnCode(params, data );
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
